package com.starrin.trashtalk.dao;

import com.starrin.trashtalk.PersistenceListener;
import com.starrin.trashtalk.model.Player;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;

public class PlayerDAOImpl implements PlayerDAO {

    @Override
    public boolean registerNewPlayer(String firstName, String lastName, String email, Date dateOfBirth, String sex, String password) {
        //Save player to database
        EntityManager em = PersistenceListener.createEntityManager();
        Player player = new Player(firstName, lastName, email, dateOfBirth, sex, password);
        em.getTransaction().begin();
        em.persist(player);
        em.getTransaction().commit();
        em.close();
        return true;
    }

    @Override
    public Player findPlayer(String email) {
        EntityManager em = PersistenceListener.createEntityManager();
        Query query = em.createQuery("from Player where email = :email").setParameter("email", email);
        try {
            return (Player) query.getSingleResult();
        } catch(NoResultException e) {
            return null;
        } finally {
            em.close();
        }
    }

    @Override
    public List<Player> findAllPlayers() {
        EntityManager em = PersistenceListener.createEntityManager();
        Query query = em.createQuery("from Player");
        List<Player> players = query.getResultList();
        em.close();
        return players;
    }

    @Override
    public Player findById(Long id) {
        EntityManager em = PersistenceListener.createEntityManager();
        Player player = em.find(Player.class, id);
        em.close();
        return player;
    }

}
